package com.zmn.plat.admin.controller.online.service.group.city;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.plat.common.constant.BaseAreaConsts;
import com.zmn.plat.model.entity.area.AreaQuery;
import com.zmn.plat.model.entity.area.BaseArea;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import com.zmn.plat.model.entity.online.service.group.city.OnlineServiceGroupCity;
import com.zmn.plat.model.entity.online.service.group.city.OnlineServiceGroupCityQuery;

/**
 * 在线客服分组城市配置
 *
 * @author linfeng
 *
 * @since 2021-03-26 17:21:53
 */
@Controller
@RequestMapping("/online/service/group/city/")
public class OnlineServiceGroupCityListController extends OnlineServiceGroupCityBaseController {
    /**
     * 城市配置详情
     * @author linfeng
     * @param groupId
     * @since 2021/03/29 14:47
     */
    @RequestMapping("detail")
    @RequiresPermissions("/online/service/group/city/detail.action")
    public ModelAndView detail(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId){
        // 1.加载 省--》城市
        List<BaseArea> provinces = baseAreaService.listByParentId(GlobalConsts.TOP_ID);
        provinces = provinces.stream().filter(e -> Objects.equals(GlobalConsts.YES, e.getStatus())).collect(Collectors.toList());
        // 加载城市
        AreaQuery cityQuery = new AreaQuery();
        cityQuery.setLevel(BaseAreaConsts.AREA_LEVEL_THREE);
        cityQuery.setStatus(GlobalConsts.YES);
        List<BaseArea> citys = baseAreaService.listByQuery(cityQuery);
        Map<Integer, List<BaseArea>> cityMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(citys)) {
            cityMap = citys.stream().collect(Collectors.groupingBy(BaseArea::getParentId));
        }

        OnlineServiceGroupCityQuery query = new OnlineServiceGroupCityQuery();
        query.setGroupId(groupId);
        List<OnlineServiceGroupCity> selectedCitys = onlineServiceGroupCityService.listByQuery(query);
        List<Integer> selectedCityIds = selectedCitys.stream().map(e -> e.getCityId()).collect(Collectors.toList());

        ModelAndView mav = new ModelAndView("online/service/group/city/cityconfig");
        mav.addObject("flag", 2);
        mav.addObject("provinces", provinces);
        mav.addObject("cityMap", cityMap);
        mav.addObject("groupId", groupId);
        mav.addObject("selectedCityIds", selectedCityIds);
        return mav;
    }

}
